package com.asimplefox.controllers;

import com.asimplefox.configs.ProxyConfig;
import com.asimplefox.service.abst.ResultU;
import com.asimplefox.service.stand.LoginDetailService;
import com.xkcoding.http.config.HttpConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthGoogleRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;

@RestController
@RequestMapping("/google")
public class GoogleAuthController implements ResultU {

    @Value("${google.client-id}")
    private String clientid;
    @Value("${google.client-secret}")
    private String clientsecret;
    @Value("${google.redirect-uri}")
    private String redirecturi;

    @RequestMapping("/login")
    public Object renderAuth(@RequestParam(value = "now",defaultValue = "true") Boolean now, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        if (now) {
            response.sendRedirect(authorizeUrl);
            return null;
        } else {
            return result(200, "success", "url", authorizeUrl);
        }
    }

    @Autowired
    LoginDetailService loginDetailService;

    @RequestMapping("/callback")
    public Object login(AuthCallback callback, HttpServletRequest request,HttpServletResponse response) {
        AuthRequest authRequest = getAuthRequest();
        return loginDetailService.loginNowWithGoogle(authRequest.login(callback),request,response);
    }

    @Autowired(required = false)
    ProxyConfig proxyConfig;

    private AuthRequest getAuthRequest() {
        HttpConfig.HttpConfigBuilder builder = HttpConfig.builder().timeout(15000);
        if (proxyConfig != null) {
            builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyConfig.getHost(), proxyConfig.getPort())));
        }
        return new AuthGoogleRequest(AuthConfig.builder()
                .clientId(clientid)
                .clientSecret(clientsecret)
                .redirectUri(redirecturi)
                .httpConfig(builder.build())
                .build());
    }
}